import React, { useState, useEffect } from 'react'
import { Card, Table, Button, Tag, Space, Modal, Form, Input, Select, message, Row, Col, Avatar, Rate } from 'antd'
import { PlusOutlined, EditOutlined, DeleteOutlined, EyeOutlined, SearchOutlined, PhoneOutlined } from '@ant-design/icons'

interface ServiceItem {
  id: string
  name: string
  type: 'medical' | 'education' | 'transportation' | 'agricultural' | 'other'
  provider: string
  contact: string
  village: string
  address: string
  description: string
  rating: number
  reviews: number
  status: 'active' | 'inactive' | 'pending'
  createdDate: string
  serviceHours: string
  priceRange: string
}

const RuralServiceManagement: React.FC = () => {
  const [services, setServices] = useState<ServiceItem[]>([])
  const [loading, setLoading] = useState(true)
  const [isModalVisible, setIsModalVisible] = useState(false)
  const [editingService, setEditingService] = useState<ServiceItem | null>(null)
  const [searchText, setSearchText] = useState('')

  // mock数据 - 与用户端RuralService页面关联
  useEffect(() => {
    const mockData: ServiceItem[] = [
      {
        id: '1',
        name: '幸福村卫生站',
        type: 'medical',
        provider: '张医生',
        contact: '13800138000',
        village: '幸福村',
        address: '幸福村村委会旁',
        description: '提供基础医疗服务、健康咨询、疫苗接种等',
        rating: 4.5,
        reviews: 23,
        status: 'active',
        createdDate: '2024-01-15',
        serviceHours: '08:00-17:00',
        priceRange: '免费-50元'
      },
      {
        id: '2',
        name: '和平村小学',
        type: 'education',
        provider: '李老师',
        contact: '13900139000',
        village: '和平村',
        address: '和平村中心广场',
        description: '提供小学教育服务，开设语文、数学、英语等课程',
        rating: 4.8,
        reviews: 15,
        status: 'active',
        createdDate: '2024-02-01',
        serviceHours: '07:30-16:30',
        priceRange: '免费'
      },
      {
        id: '3',
        name: '农产品运输服务',
        type: 'transportation',
        provider: '王师傅',
        contact: '13700137000',
        village: '富裕村',
        address: '富裕村物流中心',
        description: '提供农产品运输服务，覆盖周边乡镇',
        rating: 4.2,
        reviews: 8,
        status: 'active',
        createdDate: '2024-01-20',
        serviceHours: '06:00-20:00',
        priceRange: '50-200元'
      },
      {
        id: '4',
        name: '农业技术指导站',
        type: 'agricultural',
        provider: '赵技术员',
        contact: '13600136000',
        village: '幸福村',
        address: '幸福村农业合作社',
        description: '提供农业技术指导、病虫害防治等服务',
        rating: 4.7,
        reviews: 12,
        status: 'pending',
        createdDate: '2024-03-01',
        serviceHours: '08:30-17:30',
        priceRange: '免费'
      },
      {
        id: '5',
        name: '乡村金融服务点',
        type: 'other',
        provider: '农村信用社',
        contact: '13800138005',
        village: '和平村',
        address: '和平村商业街',
        description: '提供存取款、贷款申请、理财咨询等金融服务',
        rating: 4.6,
        reviews: 18,
        status: 'active',
        createdDate: '2024-02-10',
        serviceHours: '09:00-16:00',
        priceRange: '免费'
      },
      {
        id: '6',
        name: '农产品电商服务站',
        type: 'other',
        provider: '电商服务中心',
        contact: '13800138006',
        village: '富裕村',
        address: '富裕村电商产业园',
        description: '提供农产品电商销售、包装、物流等一站式服务',
        rating: 4.9,
        reviews: 25,
        status: 'active',
        createdDate: '2024-02-15',
        serviceHours: '08:00-18:00',
        priceRange: '服务费10-50元'
      },
      {
        id: '7',
        name: '乡村法律援助中心',
        type: 'other',
        provider: '法律援助中心',
        contact: '13800138007',
        village: '幸福村',
        address: '幸福村司法所',
        description: '提供法律咨询、法律援助、纠纷调解等服务',
        rating: 4.8,
        reviews: 16,
        status: 'active',
        createdDate: '2024-02-20',
        serviceHours: '08:30-17:00',
        priceRange: '免费'
      },
      {
        id: '8',
        name: '乡村文化活动中心',
        type: 'other',
        provider: '文化站',
        contact: '13800138008',
        village: '和平村',
        address: '和平村文化广场',
        description: '提供图书借阅、文化活动、文艺演出等服务',
        rating: 4.7,
        reviews: 14,
        status: 'active',
        createdDate: '2024-02-25',
        serviceHours: '08:00-20:00',
        priceRange: '免费'
      },
      {
        id: '9',
        name: '乡村就业服务中心',
        type: 'other',
        provider: '就业服务局',
        contact: '13800138009',
        village: '富裕村',
        address: '富裕村就业服务大厅',
        description: '提供就业信息、技能培训、创业指导等服务',
        rating: 4.5,
        reviews: 12,
        status: 'active',
        createdDate: '2024-03-01',
        serviceHours: '08:30-17:30',
        priceRange: '免费'
      },
      {
        id: '10',
        name: '乡村快递服务站',
        type: 'transportation',
        provider: '快递公司',
        contact: '13800138010',
        village: '所有村庄',
        address: '各村快递点',
        description: '提供快递收发、包裹寄存、物流配送等服务',
        rating: 4.4,
        reviews: 20,
        status: 'active',
        createdDate: '2024-03-05',
        serviceHours: '08:00-19:00',
        priceRange: '快递费5-20元'
      }
    ]

    setTimeout(() => {
      setServices(mockData)
      setLoading(false)
    }, 1000)
  }, [])

  const columns = [
    {
      title: '服务名称',
      dataIndex: 'name',
      key: 'name',
      width: 150,
      render: (text: string, record: ServiceItem) => (
        <div>
          <div style={{ fontWeight: 'bold', marginBottom: '4px' }}>{text}</div>
          <div style={{ fontSize: '12px', color: '#666' }}>{record.village}</div>
        </div>
      )
    },
    {
      title: '服务类型',
      dataIndex: 'type',
      key: 'type',
      width: 100,
      render: (type: string) => {
        const typeMap = {
          medical: { text: '医疗服务', color: 'red' },
          education: { text: '教育服务', color: 'blue' },
          transportation: { text: '交通服务', color: 'green' },
          agricultural: { text: '农业服务', color: 'orange' },
          other: { text: '其他服务', color: 'gray' }
        }
        const config = typeMap[type as keyof typeof typeMap]
        return <Tag color={config.color}>{config.text}</Tag>
      }
    },
    {
      title: '服务提供方',
      dataIndex: 'provider',
      key: 'provider',
      width: 120,
      render: (provider: string) => (
        <div style={{ display: 'flex', alignItems: 'center', gap: '8px' }}>
          <Avatar size="small" style={{ backgroundColor: '#52c41a' }}>
            {provider.charAt(0)}
          </Avatar>
          {provider}
        </div>
      )
    },
    {
      title: '联系方式',
      dataIndex: 'contact',
      key: 'contact',
      width: 120,
      render: (contact: string) => (
        <div style={{ display: 'flex', alignItems: 'center', gap: '4px' }}>
          <PhoneOutlined style={{ color: '#52c41a' }} />
          {contact}
        </div>
      )
    },
    {
      title: '服务评价',
      key: 'rating',
      width: 150,
      render: (record: ServiceItem) => (
        <div>
          <Rate disabled defaultValue={record.rating} style={{ fontSize: '14px' }} />
          <div style={{ fontSize: '12px', color: '#666', marginTop: '4px' }}>
            {record.rating}分 ({record.reviews}条评价)
          </div>
        </div>
      )
    },
    {
      title: '服务状态',
      dataIndex: 'status',
      key: 'status',
      width: 100,
      render: (status: string) => {
        const statusMap = {
          active: { text: '正常', color: 'green' },
          inactive: { text: '停用', color: 'red' },
          pending: { text: '待审核', color: 'orange' }
        }
        const config = statusMap[status as keyof typeof statusMap]
        return <Tag color={config.color}>{config.text}</Tag>
      }
    },
    {
      title: '创建时间',
      dataIndex: 'createdDate',
      key: 'createdDate',
      width: 120
    },
    {
      title: '操作',
      key: 'action',
      width: 200,
      render: (record: ServiceItem) => (
        <Space size="small">
          <Button type="link" size="small" icon={<EyeOutlined />}>查看</Button>
          <Button 
            type="link" 
            size="small" 
            icon={<EditOutlined />}
            onClick={() => handleEdit(record)}
          >
            编辑
          </Button>
          <Button type="link" size="small" icon={<DeleteOutlined />} danger>删除</Button>
          {record.status === 'pending' && (
            <Button type="link" size="small">审核通过</Button>
          )}
        </Space>
      )
    }
  ]

  const handleAdd = () => {
    setEditingService(null)
    setIsModalVisible(true)
  }

  const handleEdit = (record: ServiceItem) => {
    setEditingService(record)
    setIsModalVisible(true)
  }

  const handleSubmit = (values: any) => {
    if (editingService) {
      // 编辑现有服务
      setServices(services.map(item => 
        item.id === editingService.id 
          ? { ...item, ...values }
          : item
      ))
      message.success('服务信息更新成功')
    } else {
      // 添加新服务
      const newService: ServiceItem = {
        id: Date.now().toString(),
        name: values.name,
        type: values.type,
        provider: values.provider,
        contact: values.contact,
        village: values.village,
        address: values.address,
        description: values.description,
        rating: 0,
        reviews: 0,
        status: 'pending',
        createdDate: new Date().toISOString().split('T')[0],
        serviceHours: values.serviceHours,
        priceRange: values.priceRange
      }
      setServices([newService, ...services])
      message.success('服务添加成功，等待审核')
    }
    setIsModalVisible(false)
  }

  const filteredServices = services.filter(service =>
    service.name.toLowerCase().includes(searchText.toLowerCase()) ||
    service.village.toLowerCase().includes(searchText.toLowerCase()) ||
    service.provider.toLowerCase().includes(searchText.toLowerCase())
  )

  return (
    <div style={{ padding: '24px', background: '#f5f5f5', minHeight: '100vh' }}>
      <Card 
        title="乡村服务管理"
        extra={
          <Button type="primary" icon={<PlusOutlined />} onClick={handleAdd}>
            添加服务
          </Button>
        }
      >
        {/* 搜索和筛选 */}
        <Row gutter={16} style={{ marginBottom: '16px' }}>
          <Col span={8}>
            <Input
              placeholder="搜索服务名称、村庄或提供方"
              prefix={<SearchOutlined />}
              value={searchText}
              onChange={e => setSearchText(e.target.value)}
            />
          </Col>
          <Col span={8}>
            <Select placeholder="选择服务类型" style={{ width: '100%' }} allowClear>
              <Select.Option value="medical">医疗服务</Select.Option>
              <Select.Option value="education">教育服务</Select.Option>
              <Select.Option value="transportation">交通服务</Select.Option>
              <Select.Option value="agricultural">农业服务</Select.Option>
              <Select.Option value="other">其他服务</Select.Option>
            </Select>
          </Col>
          <Col span={8}>
            <Select placeholder="选择服务状态" style={{ width: '100%' }} allowClear>
              <Select.Option value="active">正常</Select.Option>
              <Select.Option value="inactive">停用</Select.Option>
              <Select.Option value="pending">待审核</Select.Option>
            </Select>
          </Col>
        </Row>

        <Table
          loading={loading}
          columns={columns}
          dataSource={filteredServices}
          rowKey="id"
          pagination={{
            total: filteredServices.length,
            pageSize: 10,
            showSizeChanger: true,
            showQuickJumper: true,
            showTotal: (total, range) => 
              `第 ${range[0]}-${range[1]} 条，共 ${total} 条服务`
          }}
        />
      </Card>

      {/* 添加/编辑弹窗 */}
      <Modal
        title={editingService ? '编辑服务' : '添加服务'}
        open={isModalVisible}
        onCancel={() => setIsModalVisible(false)}
        footer={null}
        width={800}
      >
        <Form
          layout="vertical"
          initialValues={editingService || {
            type: 'medical',
            village: '幸福村',
            status: 'pending'
          }}
          onFinish={handleSubmit}
        >
          <Row gutter={16}>
            <Col span={12}>
              <Form.Item
                label="服务名称"
                name="name"
                rules={[{ required: true, message: '请输入服务名称' }]}
              >
                <Input placeholder="请输入服务名称" />
              </Form.Item>
            </Col>
            <Col span={12}>
              <Form.Item
                label="服务类型"
                name="type"
                rules={[{ required: true, message: '请选择服务类型' }]}
              >
                <Select placeholder="请选择服务类型">
                  <Select.Option value="medical">医疗服务</Select.Option>
                  <Select.Option value="education">教育服务</Select.Option>
                  <Select.Option value="transportation">交通服务</Select.Option>
                  <Select.Option value="agricultural">农业服务</Select.Option>
                  <Select.Option value="other">其他服务</Select.Option>
                </Select>
              </Form.Item>
            </Col>
          </Row>

          <Row gutter={16}>
            <Col span={12}>
              <Form.Item
                label="服务提供方"
                name="provider"
                rules={[{ required: true, message: '请输入服务提供方' }]}
              >
                <Input placeholder="请输入服务提供方" />
              </Form.Item>
            </Col>
            <Col span={12}>
              <Form.Item
                label="联系方式"
                name="contact"
                rules={[{ required: true, message: '请输入联系方式' }]}
              >
                <Input placeholder="请输入联系方式" />
              </Form.Item>
            </Col>
          </Row>

          <Row gutter={16}>
            <Col span={12}>
              <Form.Item
                label="所属村庄"
                name="village"
                rules={[{ required: true, message: '请选择所属村庄' }]}
              >
                <Select placeholder="请选择所属村庄">
                  <Select.Option value="幸福村">幸福村</Select.Option>
                  <Select.Option value="和平村">和平村</Select.Option>
                  <Select.Option value="富裕村">富裕村</Select.Option>
                </Select>
              </Form.Item>
            </Col>
            <Col span={12}>
              <Form.Item
                label="服务状态"
                name="status"
                rules={[{ required: true, message: '请选择服务状态' }]}
              >
                <Select placeholder="请选择服务状态">
                  <Select.Option value="active">正常</Select.Option>
                  <Select.Option value="inactive">停用</Select.Option>
                  <Select.Option value="pending">待审核</Select.Option>
                </Select>
              </Form.Item>
            </Col>
          </Row>

          <Form.Item
            label="服务地址"
            name="address"
            rules={[{ required: true, message: '请输入服务地址' }]}
          >
            <Input placeholder="请输入服务地址" />
          </Form.Item>

          <Row gutter={16}>
            <Col span={12}>
              <Form.Item
                label="服务时间"
                name="serviceHours"
                rules={[{ required: true, message: '请输入服务时间' }]}
              >
                <Input placeholder="例如：08:00-17:00" />
              </Form.Item>
            </Col>
            <Col span={12}>
              <Form.Item
                label="价格范围"
                name="priceRange"
                rules={[{ required: true, message: '请输入价格范围' }]}
              >
                <Input placeholder="例如：免费-50元" />
              </Form.Item>
            </Col>
          </Row>

          <Form.Item
            label="服务描述"
            name="description"
            rules={[{ required: true, message: '请输入服务描述' }]}
          >
            <Input.TextArea rows={4} placeholder="请输入服务描述" />
          </Form.Item>

          <Form.Item>
            <Button type="primary" htmlType="submit" style={{ marginRight: '8px' }}>
              {editingService ? '更新' : '添加'}
            </Button>
            <Button onClick={() => setIsModalVisible(false)}>
              取消
            </Button>
          </Form.Item>
        </Form>
      </Modal>
    </div>
  )
}

export default RuralServiceManagement